package com.heima.user.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.ApUserDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.vos.ApUserImportVO;
import com.heima.model.user.vos.ApUserVO;
import com.heima.user.listen.CommonListen;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserImportAndExportService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class ApUserImportAndExportServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserImportAndExportService {

    @Autowired
    ApUserMapper apUserMapper;

    @Autowired
    StringRedisTemplate redisTemplate;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult importApUser(MultipartFile file) throws IOException {
        CommonListen<ApUserDTO> commonListen1 = new CommonListen<ApUserDTO>();
        CommonListen<ApUserDTO> commonListen2 = new CommonListen<ApUserDTO>();
        EasyExcel.read(file.getInputStream(), ApUserDTO.class, commonListen1).sheet(0).doRead();
        EasyExcel.read(file.getInputStream(), ApUserDTO.class, commonListen2).sheet(1).doRead();
        // 获取导入的数据集合
        List<ApUserDTO> list1 = commonListen1.getList();
        List<ApUserDTO> list2 = commonListen2.getList();

        long successNumber = 0;
        List<ApUserDTO> list = new ArrayList();
        List<ApUserDTO> repetitionList = new ArrayList();
        String phone = redisTemplate.opsForValue().get("phone");
        String[] split = phone.split("/");
        boolean flag = true;
        for (ApUserDTO apUser : list1) {
            for (String s : split) {
                if (apUser.getPhone().equals(s)) {
                    repetitionList.add(apUser);
                    flag = false;
                    break;
                }
            }
            if (flag) {
                apUser.setCreatedTime(new Date());
                apUser.setStatus(false);
                apUser.setFlag((short) 0);
                list.add(apUser);
                phone += apUser.getPhone() + "/";
                successNumber++;
                if (list.size() == 1000) {
                    apUserMapper.insertApUsers(list);
                    list = new ArrayList<>();
                }
            }
            flag = true;
        }
        redisTemplate.opsForValue().set("phone", phone);
        String repetitionId = "";
        //TODO 存入redis
        String uuid = UUID.randomUUID().toString();
        String apUser = "";
        for (ApUserDTO apUserDTO : repetitionList) {
            apUser += JSONObject.toJSONString(apUserDTO) + "/";
        }
        redisTemplate.opsForValue().set(uuid, apUser);
        Long repetitionNumber = Long.valueOf(repetitionList.size());
        ApUserImportVO apUserImportVO = new ApUserImportVO(repetitionNumber, successNumber, uuid);
//        list2.forEach(System.out::println);
        return ResponseResult.okResult(apUserImportVO);
    }


    @Override
    public ResponseResult exportApUser(String repetitionId, HttpServletResponse response) throws IOException {
        //1.设置响应数据的类型:excel
        response.setContentType("application/vnd.ms-excel");
        //2.设置响应数据的编码格式
        response.setCharacterEncoding("utf-8");
        List<ApUserVO> list = new ArrayList<>();
        String apUsers = redisTemplate.opsForValue().get(repetitionId);
        String[] split = apUsers.split("/");
        for (String apUser : split) {
            ApUserVO apUserVO = JSONObject.parseObject(apUser, ApUserVO.class);
            if(apUserVO.getSex().equals("false")){
                apUserVO.setSex("男");
            }else{
                apUserVO.setSex("女");
            }
            list.add(apUserVO);
        }

        EasyExcel.write(response.getOutputStream(), ApUserVO.class).excelType(ExcelTypeEnum.XLS).sheet("未成功导入数据").doWrite(list);
        return ResponseResult.okResult();
    }


}
